<?php

namespace plugin\laoha\app\model;


use plugin\admin\app\model\User;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use support\Db;

class Act extends Base
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'ha_acts';


    protected $fillable = [
        'root','root_id', 'root_type', 'user_id', 'act'
    ];

    public function root(): MorphTo
    {
        return $this->morphTo();
    }

    public function add($root,$root_id, $act)
    {
        //$acts = config('plugin.laoha.set.app.post.acts');
        //if(!isset($acts[$act])) return false;
        if (!user_id()) return false;
        $maps = plugin_config_merge('morphmaps');
        if(!isset($maps[$root])){
            return false;
        }
        return self::firstOrcreate([
            'act' => $act,
            'root' => $root,
            'root_type' => $maps[$root],
            'root_id' => $root_id,
            'user_id' => user_id()
        ]);
    }

    /**
     * 默认删除自己的
     * $user_id为false或0时，删除此记录所有
     */
    public function del($root,$root_id, $act)
    {
        if (!user_id()) return false;
        return self::where('act', $act)->where('root', $root)->where('root_id', $root_id)->where('user_id', user_id())->delete();
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}
